<template>
    <div class="relative w-full bg-white rounded-lg border-1">

        <div class="flex justify-end px-2 mt-1 text-right">
            <div class="px-2 py-1 rounded-full border-1 text-10px" @click="clearCanvas">重写</div>
        </div>

        <canvas ref="canvasRef"
                class="h-[200px] w-full border-[0] "
                @mousedown="startDrawing"
                @mousemove="draw"
                @mouseup="stopDrawing"
                @mouseleave="stopDrawing"
                @touchstart="handleTouchStart"
                @touchmove="handleTouchMove"
                @touchend="stopDrawing" />
        <div v-if="showMask"
             class="flex-center absolute top-0 left-0 w-full h-full z-10 select-none pointer-events-none">
            <span class="text-30px text-#999">请再此签名</span>
        </div>
    </div>
</template>

<script setup >
import { showToast } from '@nutui/nutui';
import { ref, onMounted, onUnmounted } from 'vue';


const emits = defineEmits(["confirm"])
const showMask = ref(true)

const canvasRef = ref(null);
const isDrawing = ref(false);
const lastX = ref(0);
const lastY = ref(0);
const ctx = ref(null);

// 初始化画布
const initCanvas = () => {
    const canvas = canvasRef.value;
    ctx.value = canvas.getContext('2d');

    resizeCanvas();

    // 设置绘图样式
    ctx.value.strokeStyle = '#000000';
    ctx.value.lineWidth = 2;
    ctx.value.lineCap = 'round';
    ctx.value.lineJoin = 'round';
};

// 调整画布大小
const resizeCanvas = () => {
    const canvas = canvasRef.value;
    const container = canvas.parentElement;
    canvas.width = container.offsetWidth;
    canvas.height = container.offsetHeight * 0.7;
};

// 开始绘制
const startDrawing = (e) => {
    isDrawing.value = true;
    [lastX.value, lastY.value] = getPosition(e);
};

// 绘制中
const draw = (e) => {
    if (!isDrawing.value) return;

    showMask.value = false

    ctx.value.beginPath();
    ctx.value.moveTo(lastX.value, lastY.value);

    const [x, y] = getPosition(e);
    ctx.value.lineTo(x, y);
    ctx.value.stroke();

    lastX.value = x;
    lastY.value = y;
};

// 停止绘制
const stopDrawing = () => {
    isDrawing.value = false;
};

// 获取坐标位置
const getPosition = (e) => {
    const canvas = canvasRef.value;
    const rect = canvas.getBoundingClientRect();

    if (e.type.includes('touch')) {
        const touch = e.touches[0] || e.changedTouches[0];
        return [
            touch.clientX - rect.left,
            touch.clientY - rect.top
        ];
    } else {
        return [
            e.clientX - rect.left,
            e.clientY - rect.top
        ];
    }
};

// 触摸事件处理
const handleTouchStart = (e) => {
    e.preventDefault();
    startDrawing(e);
};

const handleTouchMove = (e) => {
    e.preventDefault();
    draw(e);
};

// 清除画布
const clearCanvas = () => {
    showMask.value = true
    const canvas = canvasRef.value;
    ctx.value.clearRect(0, 0, canvas.width, canvas.height);
};

// // 保存签名
// const saveSignature = () => {
//     const canvas = canvasRef.value;

//     // 检查画布是否为空
//     if (isCanvasBlank(canvas)) {
//         uploadStatus.value = { error: true, message: '请先签名' };
//         return;
//     }

//     // 将画布转为Blob对象
//     canvas.toBlob((blob) => {
//         emits("confirm", blob)
//     }, 'image/png', 0.8);
// };

// 获取签名文件
const getFile = () => {

    return new Promise((resolve, reject) => {

        const canvas = canvasRef.value;

        // 检查画布是否为空
        if (isCanvasBlank(canvas)) {
            showToast.fail("请签名")
            return reject();
        }

        // 将画布转为Blob对象
        canvas.toBlob((blob) => {
            resolve(blob)
        }, 'image/png', 0.8);
    })
}


// 检查画布是否为空
const isCanvasBlank = (canvas) => {
    const blank = document.createElement('canvas');
    blank.width = canvas.width;
    blank.height = canvas.height;
    return canvas.toDataURL() === blank.toDataURL();
};

// 生命周期钩子
onMounted(() => {
    initCanvas();
    window.addEventListener('resize', resizeCanvas);
});

onUnmounted(() => {
    window.removeEventListener('resize', resizeCanvas);
});
defineExpose({
    confirm: () => getFile()
})
</script>

<style scoped>
canvas {
    touch-action: none;
    /* 禁用触摸默认行为 */
}
</style>
